package xh.lumt.server.processors;

import com.alibaba.fastjson.JSON;
import io.netty.handler.codec.http.FullHttpResponse;
import xh.lumt.util.HttpUtils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;

/**
 * Created by Administrator on 2016/6/25.
 */
public class AjaxRequestProcessor extends AbstractProcessor {

    private String uri;

    public AjaxRequestProcessor(String uri) {
        this.uri = uri;
    }

    public FullHttpResponse process() {

        String respTxt = invokeByName(uri);

        if (respTxt == null) {
            return HttpUtils._404();
        }

        FullHttpResponse response = defaultResponse(respTxt);
        response.headers().set(CONTENT_TYPE, "application/json;charset=UTF-8");
        return response;
    }

    private String now() {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("ret", 0);
        result.put("time", System.currentTimeMillis());
        return JSON.toJSONString(result);
    }

    private String playerStatus() {

        Map<String, Object> result = new HashMap<String, Object>();
        result.put("ret", 0);

        return JSON.toJSONString(result);
    }



    /**
     * uri: a/b/c =>  method: a_b_c
     */
    private String invokeByName(String uri) {

        if (uri.startsWith("/")) {
            uri = uri.substring(1);
        }

        int p = uri.indexOf("?");
        if (p >= 0) {
            uri = uri.substring(0, p);
        }

        uri = uri.replace("/", "_");

        try {
            Method[] declaredMethods = AjaxRequestProcessor.class.getDeclaredMethods();
            for (Method m : declaredMethods) {
                if (m.getName().endsWith(uri)) {
                    m.setAccessible(true);
                    return (String) m.invoke(this, null);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
